﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CRMAdminDashboard.CrmSvc;

namespace CRMAdminDashboard
{
    public partial class FormSelectBUs : Form
    {

        #region Fields

        /// <summary>
        /// The CRM Service handle
        /// </summary>
        private CachingCrmService _svcHandle;

        #endregion

        #region Properties

        /// <summary>
        /// Contains the subset of BUs the user has selected. If null, the user has selected all the BUs.
        /// </summary>
        public Dictionary<Guid, BusinessUnit> BuFilter { get; set; }

        #endregion

        #region Entry Points

        /// <summary>
        /// Standard constructor
        /// </summary>
        public FormSelectBUs(CachingCrmService svcHandle)
        {
            _svcHandle = svcHandle;
            InitializeComponent();
        }

        #endregion

        #region Events

        private void FormSelectBUs_Load(object sender, EventArgs e)
        {
            // Load all BUs and set them checked if they were before
            foreach (BusinessUnit bu in BusinessUnit.GetAllBUs(_svcHandle))
            {
                int idx = clstBUs.Items.Add(bu);
                if (BuFilter != null)
                {
                    if (BuFilter.ContainsKey(bu.Id))
                    {
                        clstBUs.SetItemChecked(idx, true);
                    }
                }
                else
                {
                    clstBUs.SetItemChecked(idx, true);
                }
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
            if (clstBUs.CheckedItems.Count != clstBUs.Items.Count)
            {
                // some BUs are not selected -> apply filter
                BuFilter = new Dictionary<Guid, BusinessUnit>();
                foreach (BusinessUnit bu in clstBUs.CheckedItems)
                {
                    BuFilter.Add(bu.Id, bu);
                }
            }
            else
            {
                // clear filter
                BuFilter = null;
            }
            this.Close();
        }

        private void clstBUs_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            if (e.NewValue == CheckState.Checked)
            {
                btnOK.Enabled = true;
            }
            else if (clstBUs.CheckedItems.Count > 1)
            {
                btnOK.Enabled = true;

            }
            else
            {
                btnOK.Enabled = false;
            }
        }

        #endregion

    }
}
